<template>
    <div>
      <h2>人脸注册</h2>
      <input v-model="username" placeholder="请输入用户名" />
      <button @click="captureAndRegister(1)">注册</button>
      <button @click="captureAndRegister(2)">登录</button>
      <video ref="video" autoplay></video>
      <canvas ref="canvas"></canvas>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import axios from 'axios';
  
  // 存储用户名
  const username = ref('');
  // 视频元素引用
  const video = ref<HTMLVideoElement | null>(null);
  // 画布元素引用
  const canvas = ref<HTMLCanvasElement | null>(null);
  
  // 当组件挂载时，初始化摄像头获取视频流
  onMounted(() => {
    initCamera();
  });
  
  // 当组件卸载前，关闭摄像头视频流
  onBeforeUnmount(() => {
    stopCamera();
  });
  
  // 初始化摄像头，获取视频流
  const initCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      video.value!.srcObject = stream;
      video.value!.play();
    } catch (error) {
      console.error('初始化摄像头出错：', error);
    }
  };
  
  // 停止摄像头视频流
  const stopCamera = () => {
    if (video.value && video.value.srcObject) {
      const tracks = (video.value.srcObject as MediaStream).getTracks();
      tracks.forEach((track) => track.stop());
    }
  };
  
  // 捕获人脸图像并进行注册操作
  const captureAndRegister = async (da: any) => {
    const dd = da

    
    try {
      // 等待视频流稳定，可根据实际情况调整等待时间
      await new Promise((resolve) => setTimeout(resolve, 1000))
      canvas.value!.width = video.value!.videoWidth;
      canvas.value!.height = video.value!.videoHeight;
      const ctx = canvas.value!.getContext('2d');
      if (ctx) {
        ctx.drawImage(video.value!, 0, 0, canvas.value!.width, canvas.value!.height);
        const imageData = canvas.value!.toDataURL('image/jpeg');
  
        const base64Data = imageData.split(',')[1];
        const formdata = new FormData();
        formdata.append('file', base64Data);
        formdata.append('user_id', 1);
        // 调用阿里去上传到阿里去
        // 在用户表中添加一个字段，把注册图片保存到表中
        if (dd == 1) {
            const response = await axios.post('http://127.0.0.1:8000/users/fr/', formdata);
            console.log(response);
         };
         if (dd == 2) {
            const response = await axios.post('http://127.0.0.1:8000/users/bdfr/', formdata);
            console.log(response);
         };
        
      }
    } catch (error) {
      console.error('人脸注册出错：', error);
    } finally {
      stopCamera();
    }
  };





  </script>
  
  <style scoped>
  /* 调整画布的样式，使其在页面上可见 */
  canvas {
    border: 1px solid black; /* 可选：为画布添加边框以便更清晰地看到它 */
  }
  </style>